<template>
  <div class="meteor" :class="{'starry-sky': backgroundTheme == 1, 'earth': backgroundTheme == 2}">
    <canvas ref="meteor" class="canvas"></canvas>
  </div>
</template>
<script>
import Meteor from '@/utils/meteor'
export default {
  props: {
    backgroundTheme: {
      type: [String, Number]
    },
    canvasWidth: {
      type: [String, Number],
      default: () => {
        return window.innerWidth
      }
    },
    canvasHeight: {
      type: [String, Number],
      default: () => {
        return window.innerHeight
      }
    }
  },
  data () {
    return {
      stars: []
    }
  },
  mounted () {
    this.meteor()
  },
  methods: {
    meteor () {
      let that = this
      let canvas = this.$refs.meteor
      let ctx = canvas.getContext('2d')
      canvas.width = this.canvasWidth
      canvas.height = this.canvasHeight
      let width = this.canvasWidth
      let height = this.canvasHeight
      // 实例化月亮和星星。流星是随机时间生成，所以只初始化数组
      let meteors = []
      function init () {
        for (let i = 0; i < 2; i++) {
          let star = new Meteor(ctx, width, height)
          meteors.push(star)
        }
        drawStar()
      }
      function drawStar (num) {
        for (let i = 0; i < num; i++) {
          meteors[i].move()
          if (meteors[i].y > that.canvasHeight) {
            ctx.clearRect(meteors[i].x, meteors[i].y - meteors[i].height, meteors[i].width, meteors[i].height)
            meteors[i] = new Meteor(ctx, width, height)
          }
        }
      }
      init()
      setInterval(function () {
        if (that.canvasWidth === 0) {
          return false
        }
        drawStar(Math.random() > 0.7 ? 1 : 2)
      }, 30)
    }
  },
  destroyed () {
    clearInterval(window.meteorTimer)
  },
  watch: {
    canvasWidth () {
      this.meteor()
    },
    canvasHeight () {
      this.meteor()
    }
  }
}
</script>

<style scoped lang="scss">
.meteor {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  overflow: hidden;
  position: absolute;
  background: #020b32;
  &.starry-sky{
    background: url('../../assets/images/setting/theme1.jpg') no-repeat center;
    background-size: 100% 100%;
  }
  &.earth{
    background: url('../../assets/images/setting/theme2.jpg') no-repeat center;
    background-size: 100% 100%;
  }
}

.canvas {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 10;
  top: 0;
  left: 0;
}
</style>
